﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;
using Mapster;
using Quartz;
using Raffles.OA.Data;
using Raffles.OA.Utility;

namespace Raffles.OA.WebApp.Areas.Manage.Controllers
{
    /// <summary>
    /// 日 期：2024-05-28 11:03:44
    /// 描 述：任务调度控制器类
    /// </summary>
    public class AutoJobController :  BaseController<AutoJob>
    {
        /// <summary>
        /// 获取分页列表
        /// </summary>
        /// <param name="param"></param>
        /// <param name="pagination"></param>
        /// <returns></returns>
        public ActionResult GetPageListJson(BaseSearchParam param, Pagination pagination)
        {
           int totalCount=0;
           var datas=_dbContext.Queryable<AutoJob>()
                               .WhereIF(!param.KeyWord.IsEmpty(), x => x.JobGroupName.Contains(param.KeyWord.Trim())|| x.JobName.Contains(param.KeyWord.Trim()))
                               .ToPageList(pagination.PageIndex, pagination.PageSize, ref totalCount);
           return Content(DataResult<List<AutoJob>>.PageResult(datas, totalCount).ToJson());
        }

        /// <summary>
        /// Form表单
        /// </summary>
        /// <returns></returns>
        public ActionResult Form()
        {
          return View();
        }

        /// <summary>
        /// 表单保存
        /// </summary>
        /// <param name="autoJobDto"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SaveForm(AutoJobDto autoJobDto)
        {
            try
            { 
                if (!autoJobDto.CronExpression.IsEmpty() && !CronExpression.IsValidExpression(autoJobDto.CronExpression))
                { 
                    return Json(DataResult.Error("Cron表达式不合法！"));
                }
                AutoJob entity = new AutoJob();
                if (autoJobDto.Id == null)
                {
                    if(_dbContext.Queryable<AutoJob>().Any(x => x.JobGroupName == autoJobDto.JobGroupName&&x.JobName==autoJobDto.JobName))
                    {
                        return Json(DataResult.Error("任务已经存在！"));
                    }

                    autoJobDto.Adapt(entity);
                    entity.CreatedOn = DateTime.Now;
                    entity.CreatedBy = OperatorProvider.Provider.GetCurrent().Id;
                    _dbContext.Insertable<AutoJob>(entity).ExecuteCommand();
                    return Json(DataResult.Success("新增成功"));
                }
                else
                {
                    if (_dbContext.Queryable<AutoJob>().Any(x => x.Id != autoJobDto.Id && x.JobGroupName == autoJobDto.JobGroupName && x.JobName == autoJobDto.JobName))
                    {
                        return Json(DataResult.Error("任务已经存在！"));
                    }
                    entity = _dbContext.Queryable<AutoJob>().InSingle(autoJobDto.Id);
                    autoJobDto.Adapt(entity);
                    entity.UpdatedOn = DateTime.Now;
                    entity.UpdatedBy = OperatorProvider.Provider.GetCurrent().Id;
                    _dbContext.Updateable<AutoJob>(entity).ExecuteCommand();
                    return Json(DataResult.Success("编辑成功"));
                }
            }
            catch (Exception ex)
            {
                return Json(DataResult.Error($"保存失败,失败原因:{ex.Message}"));
            }
        }

        /// <summary>
        /// 数据删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult DeleteData(int id)
        {
            try
            {
                _dbContext.Deleteable<AutoJob>().In(id).ExecuteCommand();
                return Json(DataResult.Success("删除成功"));
            }
            catch (Exception ex)
            {
                return Json(DataResult.Error($"删除失败,失败原因:{ex.Message}"));
            }
        }

        /// <summary>
        /// Job暂停 执行
        /// </summary>
        /// <param name="job"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ChangeJobStatus(AutoJob job)
        {
            try
            {
                AutoJob entity = _dbContext.Queryable<AutoJob>().InSingle(job.Id);
                entity.JobStatus=job.JobStatus;
                entity.UpdatedOn = DateTime.Now;
                entity.UpdatedBy = OperatorProvider.Provider.GetCurrent().Id;
                _dbContext.Updateable<AutoJob>(entity).ExecuteCommand();
                return Json(DataResult.Success($"{EnumHelper.GetEnumDesc(typeof(JobStatusEnum), job.JobStatus)}成功"));
            }
            catch (Exception ex)
            {
                return Json(DataResult.Error($"{EnumHelper.GetEnumDesc(typeof(JobStatusEnum), job.JobStatus)}失败,失败原因:{ex.Message}"));
            }
        }
    }
}
